import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:animation/db/love.dart';

class LoveDatabase extends ChangeNotifier {
  static late Isar isar;
  // 初始化数据库
  static Future<void> initialize() async {
    final dir = await getApplicationDocumentsDirectory();
    isar = await Isar.open([LoveSchema], directory: dir.path);
  }

  // 收藏壁纸 初始为空
  final List<Love> loveImages = [];

  // 添加收藏
  Future<void> addLove(String smallPath, String largePath, String tags,
      String type, String axis) async {
    List<Love> images = await getAllLove(type, axis);
    // 通过smallPath检查是否已经收藏 有则删除
    int index = images.indexWhere((element) => element.smallPath == smallPath);
    if (index != -1) {
      removeLove(images[index]);
    } else {
      final newLove = Love()
        ..smallPath = smallPath
        ..largePath = largePath
        ..tags = tags
        ..type = type
        ..axis = axis;
      await isar.writeTxn(() async {
        await isar.loves.put(newLove);
        loveImages.add(newLove);
        notifyListeners();
      });
    }
  }

  // 删除收藏
  Future<void> removeLove(Love love) async {
    await isar.writeTxn(() async {
      await isar.loves.delete(love.id);
      loveImages.remove(love);
      notifyListeners();
    });
  }

  // 查看单个是否收藏
  Future<bool> isLove(String smallPath) async {
    // 查询是否存在
    var item =
        await isar.loves.where().filter().smallPathEqualTo(smallPath).findAll();

    return item.isNotEmpty;
  }

  // 获取所有收藏
  Future<List<Love>> getAllLove(String type, String axis) async {
    return await isar.loves
        .where()
        .filter()
        .typeEqualTo(type)
        .axisEqualTo(axis)
        .findAll();
  }


  // 删除所有 type=image 且 axis=vertical 的收藏
  Future<void> removeAllLove(String type,String axis) async {
    await isar.writeTxn(() async {
      // 查询所有满足条件的数据
      List<Love> verticalImages = await isar.loves
          .where()
          .filter()
          .typeEqualTo(type)
          .axisEqualTo(axis)
          .findAll();
      // 删除每个满足条件的数据
      for (Love love in verticalImages) {
        await isar.loves.delete(love.id);
      }
      // 更新本地缓存
      loveImages
          .removeWhere((love) => verticalImages.any((v) => v.id == love.id));
      notifyListeners();
    });
  }
}
